<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
	pageEncoding="ISO-8859-1"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<script type="text/javascript">
        $(document).ready(function () {
        	
        	 /**
             * To handle left menu toggle on page load
             */
        	$('#referencedata_li').addClass('root-level has-sub opened');
        	$('#referencedata_li_ul').toggle('click').addClass('visible');
        	$('#referencedata_li_ul').attr('style','');
            $('#referencedata_li_ul_li_' + 3).attr('style','font-weight: bold;');	

        	var initialData;
        	$.ajax({
	    		'async': false,
	    		'global': false,
	    		'url': ezopsContextPath+"/rule/getValidationRules",
	    		'datatype': "json",
	    		'success': function(data){
	    			initialData = data;
	    			console.log("initialData  "+initialData);
	    		},
	    		error: function(xhr, status, error) {
	    	        // Display a generic error for now.
	    	        showAlertError('<strong>' + 'Something went wrong. Contact to your Administrator.' + '</strong>');
	    	    }
			});
        	var mandatotylookup = {
        		    "fields": [
        		        { value: "Y", label: "Y" },
        		        { value: "N", label: "N" }
        		    ],
        		    "total": 2
        		};

        	var typelookup = {
        		    "fields": [
        		        { value: "Integer", label: "Integer" },
        		        { value: "String", label: "String" },
        		        { value: "double", label: "Decimal" },
        		        { value: "boolean", label: "boolean" }
        		    ],
        		    "total": 4
        		};
    		
        	var ezopsfieldjson;
        	$.ajax({
	    		'async': false,
	    		'global': false,
	    		'url': ezopsContextPath+"/mapping/ezopsfieldslookup",
	    		'datatype': "json",
	    		'success': function(data){
	    			ezopsfieldjson = data;
	    		}            
	    		
			});
        	var assetclassjson;
        	$.ajax({
	    		'async': false,
	    		'global': false,
	    		'url': ezopsContextPath+"/lookup/getallassets",
	    		'datatype': "json",
	    		'success': function(data){
	    			assetclassjson = data;
	    			console.log(assetclassjson);
	    		}            
	    		
			});
        	/* var initialData = [
					{ezopsFieldName: "out1",  type: "Bond", range: "0-999",   dbLookupName: "Trade01", refColumnName: "resource", mandatoryName: "Y"},
					{ezopsFieldName: "out1",  type: "Bond", range: "0-999",   dbLookupName: "Trade01", refColumnName: "resource", mandatoryName: "Y"},
					{ezopsFieldName: "out1",  type: "Bond", range: "0-999",   dbLookupName: "Trade01", refColumnName: "resource", mandatoryName: "Y"},
					{ezopsFieldName: "out1",  type: "Bond", range: "0-999",   dbLookupName: "Trade01", refColumnName: "resource", mandatoryName: "Y"},
					{ezopsFieldName: "out1",  type: "Bond", range: "0-999",   dbLookupName: "Trade01", refColumnName: "resource", mandatoryName: "Y"},
					{ezopsFieldName: "out1",  type: "Bond", range: "0-999",   dbLookupName: "Trade01", refColumnName: "resource", mandatoryName: "Y"},
					{ezopsFieldName: "out1",  type: "Bond", range: "0-999",   dbLookupName: "Trade01", refColumnName: "resource", mandatoryName: "Y"},
					{ezopsFieldName: "out1",  type: "Bond", range: "0-999",   dbLookupName: "Trade01", refColumnName: "resource", mandatoryName: "Y"}
   		                ]; */


            var GridModel = function (rules) {
                this.rules = ko.observableArray(rules);

                this.addRulesRow = function () {
                    // add a new item.
                   // if (this.rules().length < 20) {
                    	var newRule = {ezopsFieldName: "",  type: "", range: "",   dbLookupName: "", refColumnName: "", mandatoryName: "N"};
                        this.rules.push(newRule);
                    	//$("#jqxgrid").jqxGrid('addrow', null, newRule, 'last');
                    	//if (source) source.totalrecords = this.items().length;
                   		$("#jqxgrid").jqxGrid('updatebounddata');
                    //}
                };

                this.removeRulesRow = function () {
                    // remove the last item.
                    this.rules.pop();
                };
				
                this.deleteRow = function () {
                	console.log(rules.length);
                	var selectedrowindex = $("#jqxgrid").jqxGrid('getselectedrowindex');
                    console.log(selectedrowindex);
                    var rowscount = $("#jqxgrid").jqxGrid('getdatainformation').rowscount;
                    console.log(rowscount);
                    if (selectedrowindex >= 0 && selectedrowindex < rowscount) {
                        var id = $("#jqxgrid").jqxGrid('getrowid', selectedrowindex);
                        var commit = $("#jqxgrid").jqxGrid('deleterow', id);
                        this.rules.splice(selectedrowindex,1);
                    }
                	console.log(rules.length);
                };
                /* this.updateItem = function () {
                    // update the first item.
                    var item = {};
                    if (initialData.length > 0) {
                        item.name = initialData[Math.floor(Math.random() * initialData.length)].name;
                        item.sales = Math.floor(Math.random() * 500);
                        item.price = Math.floor(Math.random() * 200);
                        this.items.replace(this.items()[0], item);
                    }
                }; */
                
                this.saveOrUpdateRulesRow = function (){
                	console.log(ko.toJSON(this));
                	console.log(rules);
                	$.ajax({
       			   		 headers: { 
                		        'Accept': 'application/json',
                		        'Content-Type': 'application/json' 
                		    },
        	    		'type': 'POST',
        	    		'data': ko.toJSON(rules),
        	    		'url': ezopsContextPath+"/rule/saveValidationRules",
        	    		'datatype': "json",
        	    		'success': function(result){
        	    			//console.log(result);
        	    			//alert("Rules are succesfully saved.");
        	    			showAlertSuccess('<strong>' + 'Rules are succesfully saved.' + '</strong>');
        	    		}            
        			}); 
                };
            };

		var uimodel = new GridModel(initialData);
            var source = {
                    localdata: uimodel.rules,
                    datatype: 'observablearray',
                    datafields: [
                        { name: 'ezopsFieldName', type: 'string' },
                        { name: 'mandatoryName', type: 'string' },
                        { name: 'type', type: 'string' },
                        { name: 'dbLookupName', type: 'string' },
                        { name: 'refColumnName', type: 'string' },
                        { name: 'range', type: 'string' },
                        { name: 'assetName', type: 'string' }],
                        
                        addrow: function (rowid, rowdata, position, commit) {
                            // synchronize with the server - send insert command
                            // call commit with parameter true if the synchronization with the server is successful 
                            //and with parameter false if the synchronization failed.
                            commit(true);
                        },
                        deleterow: function (rowid, commit) {
                            commit(true);
                        },
                        updaterow: function (rowid, rowdata, commit) {
                            // synchronize with the server - send update command
                            // call commit with parameter true if the synchronization with the server is successful 
                            // and with parameter false if the synchronization failder.
                            commit(true);
                        }
                };
            var dataAdapter = new $.jqx.dataAdapter(source);
            /* var getEditorDataAdapter = function (datafield) {
            	var source = {
                        localdata: uimodel.rules,
                        datatype: 'observablearray',
                        datafields: [
                            { name: 'ezopsFieldName', type: 'string' },
                            { name: 'mandatoryName', type: 'string' },
                            { name: 'type', type: 'string' },
                            { name: 'dbLookupName', type: 'string' },
                            { name: 'refColumnName', type: 'string' },
                            { name: 'range', type: 'string' },
                            { name: 'assetName', type: 'string' }]
                    };
            	var dataAdapter = new $.jqx.dataAdapter(source);
                return dataAdapter;
            };
 */
            $("#jqxgrid").jqxGrid(
                    {
						source: dataAdapter,              
                		editable: true,
                        width: '99%',
                        autorowheight: true,
                        autoheight: true,
                        pageable: true,
                        columnsresize: true,
                		columns: [
               			{ text: 'EZOPS Field', align: 'center', dataField: 'ezopsFieldName', width: '22%',columntype: 'dropdownlist', displayfield: 'ezopsFieldName', pinned: true,
               				createeditor: function (row, cellvalue, editor) {
                         	editor.jqxDropDownList({ displayMember: 'ezopsFieldName', valueMember: 'ezopsFieldId', source: ezopsfieldjson });
                   		}
                   		},
                  		{ text: 'Type', align: 'center', dataField: 'type', width: '17%', pinned: true },
                  		{ text: 'Range', dataField: 'range', align: 'center', width: '15%',minWidth: 100, pinned: true  },
                  		{ text: 'DB Lookup', dataField: 'dbLookup', columntype: 'dropdownlist', displayfield: 'dbLookupName', align: 'center' , width: '15%', pinned: true },
                  		/* { text: 'Ref Column', align: 'center', dataField: 'refColumn', columntype: 'dropdownlist', displayfield: 'refColumnName', width: '15%',minWidth: 100 , pinned: true }, */
                  		{ text: 'Mandatory', align: 'center', dataField: 'mandatoryName', columntype: 'dropdownlist', displayfield: 'mandatoryName', width: '10%', pinned: true,  
                  			createeditor: function (row, cellvalue, editor, cellText, width, height) {
                        	editor.jqxDropDownList({ displayMember: 'label', valueMember: 'value', source: mandatotylookup.fields });
                			}
                		},
                		{
                          text: 'Asset Types',  align: 'center', columntype: 'template', datafield: 'assetName', pinned: true,width: '23%',
                          createeditor: function (row, cellvalue, editor, cellText, width, height) {
                              // construct the editor. 
                              editor.jqxDropDownList({ 
                                  checkboxes: true, source: assetclassjson, displayMember: 'assetName', valueMember: 'assetName',
                                  selectionRenderer: function () {
                                      return "<span style='top:4px; position: relative;'>Please Choose:</span>";
                                  }
                              });
                          },
                          initeditor: function (row, cellvalue, editor, celltext, pressedkey) {
                              // set the editor's current value. The callback is called each time the editor is displayed.
                              var items = editor.jqxDropDownList('getItems');
                              editor.jqxDropDownList('uncheckAll');
                              if(cellvalue != null){
                              var values = cellvalue.split(/,\s*/);
                              for (var j = 0; j < values.length; j++) {
                                  for (var i = 0; i < items.length; i++) {
                                      if (items[i].label === values[j]) {
                                          editor.jqxDropDownList('checkIndex', i);
                                      }
                                  }
                              }
                            }
                          },
                          geteditorvalue: function (row, cellvalue, editor) {
                              // return the editor's value.
                              return editor.val();
                          }
                      }
                	]
            	});
            
         	 // initialize the popup window and buttons.

						ko.applyBindings(uimodel,document.getElementById('rulemapping'));
					});
</script>
<div class="panel panel-default" id="rulemapping">
	<div class="panel-heading">
		<div class="panel-title">
			<div class="pull-left">
				<!-- <a class="btn btn-default btn-icon icon-left" 
                                            data-bind="click: addRulesRow">
                                                <i class="entypo-plus"></i> Add Row </a>
                        	<a class="btn btn-default btn-icon icon-left" 
                                            data-bind="click: deleteRow">
                                                <i class="entypo-minus"></i> Delete Selected Row </a>
                            <a class="btn btn-default btn-icon icon-left" 
                                            data-bind="click: saveOrUpdateRulesRow">
                                                <i class="entypo-database"></i> SaveUpdate </a> -->
				<strong>Validation Rules</strong>
			</div>
			<!--  <a class="btn btn-default pull-right" href="user-preference.html">Thresholds</a> -->
		</div>
	</div>
	<!-- /.panel-heading -->
	<div class="panel-body">
		<div style='clear: both;'>

			<div class="exporticon-panel" style='margin: 0 1% 10px 10px;'>
				<label>Export</label> <a
					class="btn btn-primary btn-sm btn-icon icon-left excelExport"
					href="<c:url value="/fileuploaddownload/exportruleincsvandexcel?exportFileFormat='excel'"/>">
					<i class="fa fa-file-excel-o"></i> Excel
				</a> <a class="btn btn-orange btn-sm btn-icon icon-left csvExport"
					href="#"> <i class="fa fa-file-text"></i> CSV
				</a>
			</div>
			<div class="importicon-panel" style='margin: 0 1% 10px 10px;'>
				<label>Import</label> <a
					class="btn btn-orange btn-sm btn-icon icon-left" href="#"
					id='rulesImport' data-target="#uploadRuleModal" data-toggle="modal">
					<i class="fa fa-file-excel-o"></i> Excel
				</a>
			</div>
		</div>
		<div id='jqxWidget'>
			<div id="jqxgrid" style="clear: both; margin: 20px 0;">
			</div>
			<a class="btn btn-default btn-icon icon-left"
				data-bind="click: addRulesRow"> <i class="entypo-plus"></i> Add
				Row
			</a> <a class="btn btn-default btn-icon icon-left"
				data-bind="click: deleteRow"> <i class="entypo-minus"></i>
				Delete Selected Row
			</a> <a class="btn btn-default btn-icon icon-left"
				data-bind="click: saveOrUpdateRulesRow"> <i
				class="entypo-database"></i> SaveUpdate
			</a>
			<!-- <div id="popupWindow">
				<div>Select Assets Type</div>
				<div style="width: 250px; height: 100%;">
					<table>
	                    <tr>
							<td id="assets" align="right"></td>
						</tr>
	                    <tr>
	                        <td align="right"></td>
	                        <td style="padding-top: 10px;" align="right">
	                        	<input style="margin-right: 5px;" type="button" id="Save" value="Save" />
	                        	<input id="Cancel" type="button" value="Cancel" />
	                        </td>
	                    </tr>
	                </table>
	            </div>
			</div> -->
		</div>
	</div>
</div>
